class FanCarousel {
    constructor(container, options = {}) {
        this.container = container;
        this.images = options.images || [];
        this.currentIndex = options.currentIndex || 0;
        this.autoPlay = options.autoPlay !== false;
        this.autoPlayInterval = options.autoPlayInterval || 5000;
        this.onSlideChange = options.onSlideChange || (() => {});
        
        this.autoPlayTimer = null;
        this.isAnimating = false;
        this.touchStartX = 0;
        this.touchStartTime = 0;
        
        this.init();
    }
    
    init() {
        this.render();
        this.bindEvents();
        this.updateCarousel();
        if (this.autoPlay) {
            this.startAutoPlay();
        }
    }
    
    render() {
        const imagesHTML = this.images.map((image, index) => `
            <div class="carousel-item" data-index="${index}">
                <div class="image-wrapper">
                    <img src="${image.src}" alt="${image.alt || ''}" />
                </div>
            </div>
        `).join('');
        
        const indicatorsHTML = this.images.map((_, index) => `
            <div class="indicator ${index === this.currentIndex ? 'active' : ''}" data-index="${index}"></div>
        `).join('');
        
        this.container.innerHTML = `
            <div class="fan-carousel">
                <div class="carousel-track">
                    ${imagesHTML}
                </div>
                <div class="carousel-indicators">
                    ${indicatorsHTML}
                </div>
            </div>
        `;
        
        this.track = this.container.querySelector('.carousel-track');
        this.items = this.container.querySelectorAll('.carousel-item');
        this.indicators = this.container.querySelectorAll('.indicator');
    }
    
    bindEvents() {
        // 指示器点击
        this.indicators.forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                this.goToSlide(index);
            });
        });
        
        // 轮播项点击
        this.items.forEach((item, index) => {
            item.addEventListener('click', (e) => {
                // 防止拖拽时触发点击
                if (!item.classList.contains('active')) {
                    e.preventDefault();
                    this.goToSlide(index);
                }
            });
        });
        
        // 触摸事件
        this.track.addEventListener('touchstart', this.handleTouchStart.bind(this));
        this.track.addEventListener('touchmove', this.handleTouchMove.bind(this));
        this.track.addEventListener('touchend', this.handleTouchEnd.bind(this));
        
        // 鼠标事件（用于桌面测试）
        this.track.addEventListener('mousedown', this.handleTouchStart.bind(this));
        this.track.addEventListener('mousemove', this.handleTouchMove.bind(this));
        this.track.addEventListener('mouseup', this.handleTouchEnd.bind(this));
        this.track.addEventListener('mouseleave', this.handleTouchEnd.bind(this));
        
        // 暂停自动播放当鼠标悬停
        this.container.addEventListener('mouseenter', () => this.pauseAutoPlay());
        this.container.addEventListener('mouseleave', () => this.resumeAutoPlay());
    }
    
    handleTouchStart(e) {
        this.pauseAutoPlay();
        this.touchStartX = e.touches ? e.touches[0].clientX : e.clientX;
        this.touchStartTime = Date.now();
        this.track.classList.add('dragging');
    }
    
    handleTouchMove(e) {
        if (!this.touchStartX) return;
        e.preventDefault();
        
        const currentX = e.touches ? e.touches[0].clientX : e.clientX;
        const deltaX = currentX - this.touchStartX;
        
        // 计算水平平移（手势控制轮播水平移动）
        const damping = 0.4; // 阻尼系数
        const translateX = deltaX * damping;
        
        // 给整个轨道添加水平移动效果
        this.track.style.transform = `translateX(${translateX}px)`;
        this.track.style.filter = 'brightness(0.95)'; // 拖拽时稍微变暗
    }
    
    handleTouchEnd(e) {
        if (!this.touchStartX) return;
        
        const currentX = e.changedTouches ? e.changedTouches[0].clientX : e.clientX;
        const deltaX = currentX - this.touchStartX;
        const deltaTime = Date.now() - this.touchStartTime;
        const velocity = Math.abs(deltaX) / deltaTime;
        
        this.track.classList.remove('dragging');
        
        // 重置轨道变换和滤镜
        this.track.style.transform = '';
        this.track.style.filter = '';
        
        // 判断是否需要切换
        const threshold = 80;
        const fastSwipe = velocity > 0.5 && Math.abs(deltaX) > 30;
        
        if (Math.abs(deltaX) > threshold || fastSwipe) {
            if (deltaX > 0) {
                this.previousSlide();
            } else {
                this.nextSlide();
            }
        }
        
        this.touchStartX = 0;
        this.touchStartTime = 0;
        this.resumeAutoPlay();
    }
    
    goToSlide(index) {
        if (this.isAnimating || index === this.currentIndex) return;
        
        this.isAnimating = true;
        
        // 先立即隐藏所有超出范围的图片
        this.hideOutOfRangeItems(index);
        
        // 延迟一点再更新位置，避免闪现
        setTimeout(() => {
            this.currentIndex = index;
            this.updateCarousel();
        }, 50);
        
        setTimeout(() => {
            this.isAnimating = false;
        }, 800);
        
        this.onSlideChange(index, this.images[index]);
    }
    
    nextSlide() {
        const nextIndex = (this.currentIndex + 1) % this.images.length;
        this.goToSlide(nextIndex);
    }
    
    previousSlide() {
        const prevIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
        this.goToSlide(prevIndex);
    }
    
    hideOutOfRangeItems(targetIndex) {
        const totalImages = this.images.length;
        
        this.items.forEach((item, index) => {
            const offset = index - targetIndex;
            
            // 计算标准化偏移量
            let normalizedOffset = offset;
            const halfLength = Math.floor(totalImages / 2);
            if (offset > halfLength) {
                normalizedOffset = offset - totalImages;
            } else if (offset < -halfLength) {
                normalizedOffset = offset + totalImages;
            }
            
            // 如果超出可见范围，立即隐藏
            if (Math.abs(normalizedOffset) > 2) {
                item.style.display = 'none'; // 完全不显示
                item.style.transition = 'none'; // 禁用动画
            }
        });
    }

    updateCarousel() {
        const totalImages = this.images.length;
        
        this.items.forEach((item, index) => {
            const offset = index - this.currentIndex;
            
            // 处理循环边界情况 - 改进算法避免跳跃
            let normalizedOffset = offset;
            
            // 优化循环逻辑，选择最短距离
            const halfLength = Math.floor(totalImages / 2);
            if (offset > halfLength) {
                normalizedOffset = offset - totalImages;
            } else if (offset < -halfLength) {
                normalizedOffset = offset + totalImages;
            }
            
            // 限制显示范围，只显示距离当前位置2个位置以内的图片
            const isVisible = Math.abs(normalizedOffset) <= 2;
            if (!isVisible) {
                // 超出显示范围的图片完全不显示
                item.style.display = 'none';
                
                // 移除特殊样式类
                item.classList.remove('fan-active', 'fan-side', 'fan-far', 'fan-hidden');
                item.classList.add('fan-hidden');
            } else {
                item.style.display = 'block'; // 重新显示
                item.style.visibility = 'visible';
                item.style.transition = ''; // 重新启用过渡动画
                
                // 计算倾斜角度（形成扇形效果）
                const tiltAngle = normalizedOffset * 8; // 适中的倾斜角度
                
                // 计算水平位置（确保不重叠）
                const baseSpacing = 240; // 根据图片宽度调整间距，图片宽度200px，间距需要更大
                const translateX = normalizedOffset * baseSpacing;
                
                // 计算缩放、透明度和垂直偏移（底部对齐，去除前后层次感）
                const absOffset = Math.abs(normalizedOffset);
                let scale = 1;
                let opacity = 1;
                let zIndex = 5; // 所有图片相同zIndex，去除前后层次感
                let translateY = 0;
                
                if (absOffset === 0) {
                    // 当前激活的图片 - 居中最大
                    scale = 1.0;
                    opacity = 1.0;
                    zIndex = 6; // 稍微高一点点
                    translateY = 0; // 基准位置
                } else if (absOffset === 1) {
                    // 左右相邻图片 - 比中间图片稍微低一点
                    scale = 0.9; // 稍微小一点
                    opacity = 0.8;
                    zIndex = 5;
                    // 左右图片比中间图片低15px，向上调整
                    translateY = (1 - scale) * 140 + 15;
                } else if (absOffset === 2) {
                    // 第二层图片 - 更小更低
                    scale = 0.8;
                    opacity = 0.6;
                    zIndex = 5;
                    // 第二层图片比中间图片低35px，稍微向上调整
                    translateY = (1 - scale) * 140 + 35;
                }
                
                // 应用变换 - 水平平移 + 垂直偏移 + 倾斜 + 缩放
                item.style.transform = `translateX(${translateX}px) translateY(${translateY}px) rotateZ(${tiltAngle}deg) scale(${scale})`;
                item.style.opacity = opacity;
                item.style.zIndex = zIndex;
                
                // 添加特殊样式类
                item.classList.remove('fan-active', 'fan-side', 'fan-far', 'fan-hidden');
                if (absOffset === 0) {
                    item.classList.add('fan-active');
                } else if (absOffset <= 1) {
                    item.classList.add('fan-side');
                } else if (absOffset <= 2) {
                    item.classList.add('fan-far');
                }
            }
        });
        
        // 更新指示器
        this.indicators.forEach((indicator, index) => {
            indicator.classList.toggle('active', index === this.currentIndex);
        });
    }
    
    startAutoPlay() {
        if (!this.autoPlay) return;
        
        this.autoPlayTimer = setInterval(() => {
            this.nextSlide();
        }, this.autoPlayInterval);
    }
    
    pauseAutoPlay() {
        if (this.autoPlayTimer) {
            clearInterval(this.autoPlayTimer);
            this.autoPlayTimer = null;
        }
    }
    
    resumeAutoPlay() {
        if (this.autoPlay) {
            this.startAutoPlay();
        }
    }
    
    destroy() {
        this.pauseAutoPlay();
        // 移除事件监听器等清理工作
    }
}